import { queryProductList } from "@src/api/booking";
import { storeBindingsBehavior } from 'mobx-miniprogram-bindings'
import base from "@src/store/base";
import router from "@src/router";
Component({
  behaviors: [storeBindingsBehavior, router.routerBehavior],
  storeBindings: [{
    store: base,
    fields: ['themeColor', 'themeTitleColor'],
  }],
  options: {
    addGlobalClass: true
  },
  properties: {
    shopId: { type: Number },
    title: String,
    productType: Number,
    tags: Object
  },
  data: {
    productList: [],
    filterList: [],
    tagIdList: [],
    hasInit: false,
  },
  observers: {
    shopId: function (shopId) {
      if (shopId && this.data.hasInit) {
        this.setData({ tagIdList: [] })
        this.fetchData();
      }
    },
    'tagIdList,tags': function (tagIdList, tags) {
      let tagList = []
      if (tagIdList.length !== 0 && tags) {
        tagIdList.forEach(item => {
          if (tags.map[item]) {
            tagList.push({ id: item, title: tags.map[item] });
          }
        })

      };
      console.log('tagList', tagList)
      this.setData({ tagList })
    }
  },
  lifetimes: {
    ready: function () {
      this.fetchData();
      this.setData({ hasInit: true })
    },
  },
  methods: {
    fetchData() {
      let data = {
        shopId: this.data.shopId,
        productType: this.data.productType
      };
      queryProductList(data).then(res => {
        if (res.code === 0) {
          this.parseData(res.data)
        }
      })
    },
    navigateToRoomDetail(e) {
      console.log('e', e)
    },
    handleFilterTags(e) {
      let tagList = e.detail;
      let productList = this.data.productList;
      let filterList = [];
      if (!tagList || tagList.length === 0) {
        this.setData({ filterList: productList })
        return;
      }
      for (let product of productList) {
        if (this.includeTag(product, tagList)) {
          filterList.push(product);
        }
      }
      this.setData({ filterList })
    },
    includeTag(product, tags) {
      if (!product.tags) {
        return false;
      }
      for (let tag of tags) {
        if (product.tags.indexOf(String(tag)) === -1) {
          return false;
        }
      }
      return true;
    },
    parseData(productList) {
      let tagIdList = [];
      for (let product of productList) {
        let tags = [];
        if (product.tags) {
          tags = product.tags.split(",");
          tags.forEach(item => {
            if (tagIdList.indexOf(item) === -1) { tagIdList.push(item) }
          })
        }
        product['tags'] = tags;
      }
      console.log('filterList', productList)
      this.setData({ productList: productList, filterList: productList, tagIdList });
    },
  }
})
